package cn.school.demo.ui.search

import android.annotation.SuppressLint
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentSearchedBinding
import cn.school.demo.pojo.Article
import cn.school.demo.ui.article.ViewPagerFragment
import com.blankj.utilcode.util.GsonUtils
import com.bumptech.glide.Glide
import com.google.gson.reflect.TypeToken

class SearchedFragment : Fragment() {

    private lateinit var viewModel: SearchViewModel
    private lateinit var binding: FragmentSearchedBinding
    private lateinit var adapter: SearchAdapter
    private var sh: SharedPreferences? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        /*val map = GsonUtils.fromJson<Map<String, String>>(
            arguments?.getString("map"),
            object : TypeToken<Map<String, String>>() {}.type
        )
        map["text"]?.let {
            viewModel.searchContext = it
        }*/
        viewModel = ViewModelProvider(this).get(SearchViewModel::class.java)
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_searched, container, false)
        binding.vw = this
        binding.lifecycleOwner = viewLifecycleOwner
        sh = requireActivity().getSharedPreferences(
            "SearchHistory",
            androidx.appcompat.app.AppCompatActivity.MODE_PRIVATE
        )
        init()
        return binding.root
    }

    fun gotoBack() = MyApplication.goto(
        R.id.action_Searched_to_Search,
        findNavController(),
        parentFragmentManager
    )

    private fun init() {
        binding.searchedFragmentQuery.setQuery(MyApplication.searchContext as CharSequence, false)
        val result = viewModel.getSearchedResult(MyApplication.searchContext)
        result.observe(viewLifecycleOwner) {
            viewModel.setArticleList(it)
        }
        binding.searchedFragmentProgressBar.visibility = View.VISIBLE
        viewModel.isUpdate.observe(viewLifecycleOwner) {
            if (viewModel.articleList.value!![0].articleId != -1)
                updateUI()
            else {
                binding.apply {
                    searchedFragmentProgressBar.visibility = View.INVISIBLE
                    searchedFragmentRecyclerView.visibility = View.GONE
                    searchedFragmentNoData.visibility = View.VISIBLE
                }
            }
        }
        binding.searchedFragmentQuery.setOnQueryTextListener(object :
            SearchView.OnQueryTextListener {
            //当点击搜索按钮时触发该方法
            override fun onQueryTextSubmit(query: String): Boolean {
                MyApplication.searchContext = query
                viewModel.getSearchedResult(query).observe(viewLifecycleOwner) {
                    viewModel.setArticleList(it)
                }
                when (sh!!.getString(MyApplication.user!!.sfNumber.toString(), null)) {
                    null -> {
                        sh!!.edit().apply {
                            putString(
                                MyApplication.user!!.sfNumber.toString(),
                                GsonUtils.toJson(mutableListOf<String>(binding.searchedFragmentQuery.query.toString()))
                            )
                            commit()
                        }
                        viewModel.setSearchHistory(mutableListOf<String>(binding.searchedFragmentQuery.query.toString()))
                    }
                    else -> {
                        val list = GsonUtils.fromJson<ArrayList<String>>(
                            sh!!.getString(
                                MyApplication.user!!.sfNumber.toString(),
                                null
                            ),
                            object : TypeToken<ArrayList<String>>() {}.type
                        )
                        if (list.size < 4) {
                            if (!list.contains(binding.searchedFragmentQuery.query.toString()))
                                list.add(binding.searchedFragmentQuery.query.toString())
                        } else {
                            if (!list.contains(binding.searchedFragmentQuery.query.toString())) {
                                list.removeAt(0)
                                list.add(binding.searchedFragmentQuery.query.toString())
                            }
                        }
                        sh!!.edit().apply {
                            putString(
                                MyApplication.user!!.sfNumber.toString(),
                                GsonUtils.toJson(list)
                            )
                            commit()
                        }
                        viewModel.setSearchHistory(list)
                    }
                }
                return false
            }

            //当搜索内容改变时触发该方法
            override fun onQueryTextChange(newText: String): Boolean {
                return false
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun updateUI() {
        binding.apply {
            searchedFragmentProgressBar.visibility = View.INVISIBLE
            searchedFragmentRecyclerView.visibility = View.VISIBLE
            searchedFragmentNoData.visibility = View.GONE
        }
        binding.searchedFragmentRecyclerView.apply {
            adapter?.let {
                this.adapter!!.notifyDataSetChanged()
            } ?: let {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = SearchAdapter(viewModel.articleList.value!!)
            }
        }
        val articles = viewModel.articleList.value
        adapter = SearchAdapter(articles!!)
        binding.searchedFragmentRecyclerView.apply {
            adapter = adapter

        }
    }

    /*private inner class SearchHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var article: Article
        private val titleTextView = itemView.findViewById<TextView>(R.id.searched_article_title)
        private val dateTextView = itemView.findViewById<TextView>(R.id.searched_article_date)

        init {
            itemView.setOnClickListener(this)
        }

        fun bind(article: Article) {
            this.article = article
            titleTextView.text = this.article.articleName
            dateTextView.text = this.article.releaseTime.subSequence(0, 10)
        }

        override fun onClick(v: View) {
            LogUtils.e(article.articleName)
            MyApplication.apply {
                this.article = this@SearchHolder.article
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Searched.toString()
                goto(
                    R.id.action_Searched_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class SearchAdapter(var articleList: MutableList<Article>) :
        RecyclerView.Adapter<SearchedFragment.SearchHolder>() {
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): SearchedFragment.SearchHolder {
            val view = layoutInflater.inflate(R.layout.list_item_searched, parent, false)
            return SearchHolder(view)
        }

        override fun onBindViewHolder(holder: SearchedFragment.SearchHolder, position: Int) {
            val article = articleList[position]
            holder.bind(article)
        }

        override fun getItemCount() = articleList.size

    }*/
    private inner class SearchedHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var article: Article
        private val timeTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_time)
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_text)
        private val imageView =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_image_0)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bindByOneImage(article: Article, imageUrl: String) {
            this.article = article
            timeTextView.text =
                "${this.article.source} ${this.article.releaseTime.subSequence(0, 10)}"
            titleTextView.text = this.article.articleName
            Glide.with(requireContext()) //
                .load(imageUrl) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView)
        }

        @SuppressLint("SetTextI18n")
        fun bindOnlyContext(article: Article) {
            this.article = article
            timeTextView.text =
                "${this.article.source} ${this.article.releaseTime.subSequence(0, 10)}"
            titleTextView.text = this.article.articleName
            imageView.visibility = View.GONE
        }

        override fun onClick(v: View) {
            MyApplication.apply {
                this.article = this@SearchedHolder.article
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Searched.toString()
                goto(
                    R.id.action_Searched_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class SearchedThreeImageHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var article: Article
        private val timeTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_three_image_time)
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_three_image_text)
        private val imageView_1 =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_three_image_1)
        private val imageView_2 =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_three_image_2)
        private val imageView_3 =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_three_image_3)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bind(article: Article, imageUrl: List<String>) {
            this.article = article
            timeTextView.text =
                "${this.article.source} ${this.article.releaseTime.subSequence(0, 10)}"
            titleTextView.text = this.article.articleName
            Glide.with(requireContext()) //
                .load(imageUrl[0]) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView_1)
            Glide.with(requireContext()) //
                .load(imageUrl[1]) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView_2)
            Glide.with(requireContext()) //
                .load(imageUrl[2]) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView_3)
        }

        override fun onClick(v: View) {
            MyApplication.apply {
                this.article = this@SearchedThreeImageHolder.article
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Searched.toString()
                goto(
                    R.id.action_Searched_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class SearchAdapter(var ArticleList: MutableList<Article>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val ONE_IMAGE = 1
        private val MORE_IMAGE = 2
        private val NO_IMAGE = 3
        private var urlList = mutableListOf<String>()

        override fun getItemViewType(position: Int): Int {
            urlList = ViewPagerFragment.getUrlFromArticle(ArticleList[position])
            return when (urlList.size) {
                0 -> NO_IMAGE
                1 -> ONE_IMAGE
                2 -> ONE_IMAGE
                else -> MORE_IMAGE
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when (viewType) {
                NO_IMAGE -> SearchedHolder(
                    layoutInflater.inflate(
                        R.layout.list_item_view_page_home,
                        parent,
                        false
                    )
                )
                ONE_IMAGE -> SearchedHolder(
                    layoutInflater.inflate(
                        R.layout.list_item_view_page_home,
                        parent,
                        false
                    )
                )
                else -> SearchedThreeImageHolder(
                    layoutInflater.inflate(
                        R.layout.list_item_view_page_home_three_image,
                        parent,
                        false
                    )
                )
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val article = ArticleList[position]
            when (getItemViewType(position)) {
                MORE_IMAGE -> (holder as SearchedThreeImageHolder).bind(article, urlList)
                NO_IMAGE -> (holder as SearchedHolder).bindOnlyContext(article)
                ONE_IMAGE -> (holder as SearchedHolder).bindByOneImage(article, urlList[0])
            }
        }

        override fun getItemCount() = ArticleList.size
    }
}